import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { notification } from 'antd'

// 用自定义Hooks只有状态不同，把方法逻辑都封装都封装到有个组件中，再点击删除，下线的时候不知道是哪一个，所以button属性要写成箭头函数，在子组件回调的时候，带上ID

function usePublish(type) {

    const { username } = JSON.parse(localStorage.getItem("token"))
    const [dataSource, setDataSource] = useState([])

    useEffect(() => {
        axios(`/news?author=${username}&publishState=${type}&_expand=category`).then(res => {
            console.log(res.data);
            setDataSource(res.data)
        })
    }, [username, type])

    const handlePublish = (id) => {
        // console.log(id);
        setDataSource(dataSource.filter(Item => Item.id !== id))
        axios.patch(`/news/${id}`, {
            'auditState': 2,
            'publishTIme': Date.now()
        }).then(res => {
            // props.history.push('/publish-manage/published')
            notification.info({
                message: `通知`,
                description: `您可以到【发布管理/已经发布】中查看你的新闻`,
                placement: 'bottomRight',
            });
        })
    }

    const handleSunset = (id) => {
        // console.log(id);
        setDataSource(dataSource.filter(Item => Item.id !== id))
        axios.patch(`/news/${id}`, {
            "publishState": 3
        }).then(res => {
            notification.info({
                message: `通知`,
                description: `您可以到【发布管理/已下线】中查看你的新闻`,
                placement: 'bottomRight',
            });
        })
    }

    const handleDelete = (id) => {
        // console.log(id);  
        setDataSource(dataSource.filter(Item => Item.id !== id))
        axios.delete(`/news/${id}`, {
            "publishState": 3
        }).then(res => {
            notification.info({
                message: `通知`,
                description: `您已经删除已下线的新闻`,
                placement: 'bottomRight',
            });
        })
    }

    return {
        dataSource,
        handlePublish,
        handleSunset,
        handleDelete
    }
}

export default usePublish

